﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Microsoft.Win32;
using System;
using System.Deployment.Application;
using System.Drawing;
using System.IO;
using System.Windows.Forms;


namespace DevTeam.BaseForms
{
    public partial class DevLogin : XtraForm
    {

        public delegate void InitSessionHandler();
        public event InitSessionHandler InitSession;

        public delegate Session.DevApplication InitApplicationHandler();
        public event InitApplicationHandler InitApplication;

        public delegate bool CheckUserHandler(string Username, string Password, string NewPassword);
        public event CheckUserHandler CheckUser;

        public DevLogin()
        {
            InitializeComponent();
        }

        private void DevLogin_Load(object sender, EventArgs e)
        {
            if (this.DesignMode)
                return;

            if (InitSession == null)
            {
                XtraMessageBox.Show("Login formunuzda InitSession Event'ini mutlaka handle etmelisiniz !", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw new NotImplementedException();
            }
            else if (InitSession == null)
            {
                XtraMessageBox.Show("Login formunuzda InitApplication Event'ini mutlaka handle etmelisiniz !", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw new NotImplementedException();
            }
            else if (CheckUser == null)
            {
                XtraMessageBox.Show("Login formunuzda CheckUser Event'ini mutlaka handle etmelisiniz !", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw new NotImplementedException();
            }

            InitApplication();
        }


        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (txtNewPassword.Visible)
            {
                if (txtNewPassword.Text == "")
                {
                    XtraMessageBox.Show("Yeni parola boşluk olamaz. Tekrar deneyin.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else if (txtNewPassword.Text.Length < 3)
                {
                    XtraMessageBox.Show("Yeni parola 3 karakterden kısa olamaz. Tekrar deneyin.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtNewPassword.Text = "";
                    return;
                }
            }

            if (CheckUser(txtUserName.Text, txtPassword.Text, txtNewPassword.Text))
            {
                InitSession();
                if (Session.CurrentUser.PasswordHash == string.Empty)
                    btnChangePassword_OpenLink(null, null);
                else
                    this.DialogResult = DialogResult.OK;
            }
            else
            {
                txtPassword.Text = String.Empty;
                txtPassword.Focus();
            }
        }

        public string RememberUser(string UserNameToSave = "")
        {
            //TODO KG:ConfExpert ler değişmeli. uygulama ismi ile aynı olmalı
            try
            {
                RegistryKey register = Registry.CurrentUser.CreateSubKey(@"Software\ConfExpert");
                if (UserNameToSave != "")
                {
                    register.SetValue("UserLastLoggedIn", UserNameToSave, RegistryValueKind.String);
                    Registry.LocalMachine.Flush();
                }
                else
                    UserNameToSave = (string)register.GetValue("UserLastLoggedIn", String.Empty);

            }
            catch (Exception)
            {
            }
            return UserNameToSave;
        }

        private void cbDatabase_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session.isProduction = cmbDatabase.SelectedIndex == 0;
            cmbDatabase.BackColor = Session.isProduction ? Color.White : Color.YellowGreen;
        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Abort;
        }

        private void btnChangePassword_OpenLink(object sender, OpenLinkEventArgs e)
        {            
            int l = lblNewPassword.Location.Y;
            int c = txtNewPassword.Location.Y;
            lblNewPassword.Location = new Point(lblNewPassword.Location.X, lblDatabase.Location.Y);
            txtNewPassword.Location = new Point(txtNewPassword.Location.X, cmbDatabase.Location.Y);
            lblDatabase.Location = new Point(lblDatabase.Location.X, l);
            cmbDatabase.Location = new Point(cmbDatabase.Location.X, c);
            btnLogin.Location = new Point(btnLogin.Location.X, cmbDatabase.Location.Y);

            bool visible = btnChangePassword.Text == "Parola Değiştir";

            if (visible)
            {
                btnChangePassword.Text = "Parola Değiştirme";
                lblNewPassword.Visible = true;
                txtNewPassword.Visible = true;
            }
            else
            {
                btnChangePassword.Text = "Parola Değiştir";
                lblNewPassword.Visible = false;
                txtNewPassword.Visible = false;
                txtNewPassword.Text = "";
            }
        }

        private void DevLogin_Shown(object sender, EventArgs e)
        {
            cmbDatabase.SelectedIndex = 0;

            if (this.DesignMode)
                return;

            this.Text = Session.ApplicationName;
            if (ApplicationDeployment.IsNetworkDeployed)
                this.Text += " - v" + ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();

            string userName = RememberUser();
            if (userName != String.Empty)
            {
                txtUserName.Text = userName;
                txtPassword.Focus();

                FileInfo fi;
                switch (Environment.MachineName.ToUpper())
                {
                    case "ORHAN-PC":
                        fi = new FileInfo(Session.AppDataPath + "\\oku.txt");
                        if (fi.Exists)
                            txtPassword.Text = File.ReadAllText(fi.FullName).Replace(Environment.NewLine, string.Empty);
                        break;

                    case "KGULCAN":
                        cmbDatabase.SelectedIndex = 1;

                        fi = new FileInfo(@"D:\Karbel\Erişim\ce.txt");
                        if (fi.Exists)
                            txtPassword.Text = File.ReadAllText(fi.FullName);
                        break;

                    case "KADIR-PC":
                        cmbDatabase.SelectedIndex = 1;
                        break;
                }
            }
            else
                txtUserName.Focus();
        }

        private void DevLogin_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.F12)
            {
                if (File.Exists(Session.SQLiteFile))
                    File.Delete(Session.SQLiteFile);
                XtraMessageBox.Show("Tekrar giriş yapmayı deneyin.");
            }
            else if (e.KeyCode == Keys.Escape)
            {
                this.DialogResult = DialogResult.Cancel;
                Application.Exit();
            }
        }
    }
}